﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Spaanjaars.ContactManager.Infrastructure.Domain;
using Spaanjaars.ContactManager.Infrastructure.Validation;

namespace Spaanjaars.ContactManager.Model
{
    public class ContactPerson : Entity<int, ContactPerson>, IAggregateRoot 
    {        
        public ContactPerson()
		{
           
		}

        public void ChangeNameTo(Name name)
        {
            // Check that name is not NULL and is valid
            Name = name;
        }

        public Name Name { get; set; }
    	
        public void SetBirthDateTo(DateTime dateOfBirth)
        {            
            if (dateOfBirth > DateTime.Now)
                InvalidDomainObjectException.ThrowWith("dateOfBirth", null);

            DateOfBirth = dateOfBirth;
        }

        public DateTime DateOfBirth { get; set; }

        protected virtual IList<Address> Addresses
        {
            get; set;
        }
        
        public IEnumerable<Address> GetAddresses()
        {            
            foreach (Address address in Addresses)
                yield return address;
        }
        
        public void AddAddress(Address address)
        {            
            Check.ThrowExceptionIfAnyBrokenRules(address, "Changing Address");

            ContactPersonAddressFactory.CreateFrom(address, this);

            Addresses.Add(address);            
        }
      
        public override string ToString()
        {
            return String.Format("{0} born on {1}", Name.FullName, DateOfBirth.ToString());
        }

        public override IEnumerable<IBrokenRule> GetBrokenRulesFor(IDomainObjectValidator<ContactPerson> domainObjectValidator)
        {
            return domainObjectValidator.RulesBrokenBy(this);            
        }

        public override IEnumerable<IBrokenRule> GetBrokenRules()
        {
            return GetBrokenRulesFor(new ContactPersonValidator());
        }
    }
}
